package com.wanghua.spring.filter;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Filter 与 Listener 都属于 Servlet 的规范。
 * 日志记录 Filter。
 * 该日志记录 Filter 使用 apache 的 commons-logging 的，commons-logging 默认采用 Log4J 输出日志，但是 Log4J 的新版本可能 commons-logging 不支持的。所以这里用 Log4J 的 API.
 * Log4J 的输出格式可以在文件中配置：log4j.properties。
 * 这里日志会写到 web 根目录的 filter.log 中。
 */
public class LogFilter implements Filter {
    Logger log = (Logger) LogManager.getLogger("logger1");
    private String filterName;

    public void init(FilterConfig config) throws ServletException {
        filterName = config.getFilterName();
        log.info("启动 Filter：" + filterName);
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        long startTime = System.currentTimeMillis();

        String requestURI = request.getRequestURI();
        requestURI = request.getQueryString() == null ? requestURI : (requestURI + "?" + request.getQueryString());

        chain.doFilter(request, response);

        long endTime = System.currentTimeMillis();
        log.info(request.getRemoteAddr() + "访问了" + requestURI + "总用时" + (endTime - startTime) + "毫秒。");
    }

    public void destroy() {
        log.info("关闭 Filter: " + filterName);
    }
}
